﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;

namespace ReportGenerators.MuaHang
{
    public partial class FrmThongKeMuaHang : BasicForms.FrmSupportPrintableComponents
    {
        public FrmThongKeMuaHang()
        {
            InitializeComponent();
        }
       
        private void FrmThongKeMuaHang_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedIndex = 19;

                cmbKho.DataSource = GeneralLibs.SortDataAlphabetic.DataTableSort(DanhMucKho.Instance.DataTable, "Ten", 0).DefaultView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                cmbNhomVatTuHangHoa.DataSource = GeneralLibs.SortDataAlphabetic.DataTableSort(DanhMucNhomVatTuHangHoa.Instance.DataTable, "Ten", 0).DefaultView;
                cmbNhomVatTuHangHoa.DisplayColumn = "Ten";
                cmbNhomVatTuHangHoa.ValueColumn = "ID";
                cmbNhomVatTuHangHoa.AddVisibleColumn("Ma", "Mã");
                cmbNhomVatTuHangHoa.AddVisibleColumn("Ten", "Tên");

                gridControl.DataSource = dsThongKeMuaHang.Detail_ThongKeMuaHang;
                gridControlDsDoiTac.DataSource = dsThongKeMuaHang.DoiTuongNghiepVu;
                gridControlDsVatTuHangHoa.DataSource = dsThongKeMuaHang.VatTuHangHoa;

                dsThongKeMuaHang.DoiTuongNghiepVu.Merge(DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataTable);
                dsThongKeMuaHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Instance.DataTable);    //Lấy tất cả các hàng vì không dùng nhưng có thể đã mua
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
           
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsDoiTac.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }

            try
            {
                chkChooseAllDoiTac.Checked = true;
                chkChooseAllVatTuHangHoa.Checked = false;
                chkTKHangMuaTraLai.Checked = false;
                FormatNumberInGridView(gridView);
                FormatNumberInGridView(gridViewDsDoiTac);
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeMuaHang.VatTuHangHoa.Rows)
            {
                row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
            }
        }
        private void chkChooseAllDoiTac_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeMuaHang.DoiTuongNghiepVu.Rows)
            {
                row["Choose"] = chkChooseAllDoiTac.Checked;
            }
        }

        private void cmbNhomVatTuHangHoa_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNhomVatTuHangHoa.EditValue = Guid.Empty;
        }
        private void cmbNhomVatTuHangHoa_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbNhomVatTuHangHoa.EditValue is Guid && (Guid)cmbNhomVatTuHangHoa.EditValue != Guid.Empty)
                {
                    //Dieu kien loc la ID = cmbNhomVatTuHangHoa.EditValue + ID cac nhom con.
                    string filterNhomCon = "CONVERT('{" + cmbNhomVatTuHangHoa.EditValue.ToString() + "}','System.Guid'), ";
                    DanhMucNhomVatTuHangHoa cacNhomCon = DanhMucNhomVatTuHangHoa.Instance.GetNhomVatTuHangHoaCon((Guid)cmbNhomVatTuHangHoa.EditValue);
                    foreach (NhomVatTuHangHoa nhomCon in cacNhomCon)
                    {
                        filterNhomCon += "CONVERT('{" + nhomCon.ID + "}','System.Guid'), ";
                        //filterNhomCon += string.Format(", '{0}'", nhomCon.ID);
                    }
                    if (filterNhomCon.EndsWith(", ")) filterNhomCon = filterNhomCon.Remove(filterNhomCon.Length - 2);

                    dsThongKeMuaHang.VatTuHangHoa.Clear();
                    string filter = string.Format("NhomVatTuHangHoaID IN ({0}) AND TrangThai = 1 ", filterNhomCon);
                    dsThongKeMuaHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Filter(filter).DataView.ToTable());
                }
                else
                {
                    dsThongKeMuaHang.VatTuHangHoa.Clear();
                    dsThongKeMuaHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Instance.DataTable);
                }
                chkChooseAllVatTuHangHoa.Checked = false;
                chkChooseAllVatTuHangHoa.Checked = true;
                FormatNumberInGridView(gridView);
                FormatNumberInGridView(gridViewDsDoiTac);
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if(!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm \n" + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            BasicForms.FrmProgressBar.StartShowProgress();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                string nhaCungCapCondition = "1 = 1";
                if (!chkChooseAllDoiTac.Checked)
                {
                    nhaCungCapCondition = "B.DoiTuongNghiepVu1ID IN (";
                    foreach (DataRow row in dsThongKeMuaHang.DoiTuongNghiepVu.Rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            nhaCungCapCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (nhaCungCapCondition.EndsWith("', ")) nhaCungCapCondition = nhaCungCapCondition.Substring(0, nhaCungCapCondition.Length - 2) + ")";
                    else nhaCungCapCondition = "1 = 0";
                }

                string vatTuHangHoaCondition = "1 = 1";
                if (!chkChooseAllVatTuHangHoa.Checked)
                {
                    vatTuHangHoaCondition = "C.VatTuHangHoa1ID IN  (";
                    foreach (DataRow row in dsThongKeMuaHang.VatTuHangHoa.Rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                    else vatTuHangHoaCondition = "1 = 0";
                }
                else if (cmbNhomVatTuHangHoa.EditValue != null) 
                {
                    vatTuHangHoaCondition = "C.VatTuHangHoa1ID IN  (";
                    foreach (DataRow row in dsThongKeMuaHang.VatTuHangHoa.Rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                    else vatTuHangHoaCondition = "1 = 0";
                }

                string khoCondition = "1 = 1";
                if(cmbKho.EditValue != null && (Guid)cmbKho.EditValue != Guid.Empty)  khoCondition = string.Format("B.Kho1ID = '{0}'", cmbKho.EditValue);

                cmd.CommandText = string.Format("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
                cmd.ExecuteNonQuery();

                if (!chkTKHangMuaTraLai.Checked)
                {
                    cmd.CommandText = string.Format("SELECT A.So, A.Ngay, DTNV.Ten TenDoiTac, Kho.Ten TenKho, D.Ten TenHangHoa, E.Ten TenNhomHangHoa, D.DonViTinh,   \n" +
                                               "	C.Value1 SoLuong, C.Value12 GiaBia, C.Value13 ThanhTienGiaBia, C.Value8 ChietKhau, C.Value6 GiaThanhToan, \n" +
                                               "    C.Value7 ThanhTien, A.SoTienNT TongTienTheoHoaDon, PTBH.Ten PhuongThucThanhToan  \n" +
                                               "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n" +
                                               "	INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID  \n" +
                                               "	INNER JOIN  KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID  \n" +
                                               "	INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n" +
                                               "	INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                               "	INNER JOIN DoiTuongNghiepVu DTNV ON B.DoiTuongNghiepVu1ID = DTNV.ID  \n" +
                                               "	INNER JOIN Kho ON B.Kho1ID = Kho.ID  \n" +
                                               "    LEFT JOIN PhuongThucThanhToanBanHang PTBH ON A.PhuongThucThanhToanMuaBanHangID = PTBH.ID \n" +
                                               "WHERE LCT.Ma IN( 'HoaDonMuaHang' )   \n" +
                                               "	AND @ThoiDiemDau <= B.Ngay AND B.Ngay <= @ThoiDiemCuoi \n" +
                                               "	AND	{0} \n" +
                                               "	AND {1} \n" +
                                               "	AND {2} \n" ,
                                               //"ORDER BY A.Ngay \n",
                                                nhaCungCapCondition, vatTuHangHoaCondition, khoCondition);
                }
                else
                {
                    cmd.CommandText = string.Format("SELECT A.So, A.Ngay, DTNV.Ten TenDoiTac, Kho.Ten TenKho, D.Ten TenHangHoa, E.Ten TenNhomHangHoa, D.DonViTinh,   \n" +
                                               "	C.Value1 SoLuong, C.Value12 GiaBia, C.Value13 ThanhTienGiaBia, C.Value8 ChietKhau, C.Value6 GiaThanhToan, \n" +
                                               "    C.Value7 ThanhTien, A.SoTienNT TongTienTheoHoaDon , PTBH.Ten PhuongThucThanhToan \n" +
                                               "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n" +
                                               "	INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID  \n" +
                                               "	INNER JOIN  KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID  \n" +
                                               "	INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n" +
                                               "	INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                               "	INNER JOIN DoiTuongNghiepVu DTNV ON B.DoiTuongNghiepVu1ID = DTNV.ID  \n" +
                                               "	INNER JOIN Kho ON B.Kho1ID = Kho.ID  \n" +
                                               "    LEFT JOIN PhuongThucThanhToanBanHang PTBH ON A.PhuongThucThanhToanMuaBanHangID = PTBH.ID \n" +
                                               "WHERE LCT.Ma IN( 'HoaDonMuaHang' )   \n" +
                                               "	AND @ThoiDiemDau <= B.Ngay AND B.Ngay <= @ThoiDiemCuoi \n" +
                                               "	AND	{0} \n" +
                                               "	AND {1} \n" +
                                               "	AND {2} \n" +
                                               "UNION \n" +
                                               "SELECT A.So, A.Ngay, DTNV.Ten TenDoiTac, Kho.Ten TenKho, D.Ten TenHangHoa, E.Ten TenNhomHangHoa, D.DonViTinh,  \n" +
                                               "	C.Value1 SoLuong, C.Value12 GiaBia,  C.Value13 ThanhTienGiaBia, C.Value8 ChietKhau,  -C.Value6 GiaThanhToan, \n" +
                                               "   -C.Value7 ThanhTien ,-A.SoTienNT TongTienTheoHoaDon, PTBH.Ten PhuongThucThanhToan \n" +
                                               "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n" +
                                               "	INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID  \n" +
                                               "	INNER JOIN  KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID  \n" +
                                               "	INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n" +
                                               "	INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                               "	INNER JOIN DoiTuongNghiepVu DTNV ON B.DoiTuongNghiepVu1ID = DTNV.ID  \n" +
                                               "	INNER JOIN Kho ON B.Kho1ID = Kho.ID  \n" +
                                               "    LEFT JOIN PhuongThucThanhToanBanHang PTBH ON A.PhuongThucThanhToanMuaBanHangID = PTBH.ID \n" +
                                               "WHERE LCT.Ma IN( 'HangMuaTraLai' )   \n" +
                                               "	AND @ThoiDiemDau <= B.Ngay AND B.Ngay <= @ThoiDiemCuoi \n" +
                                               "	AND	{0} \n" +
                                               "	AND {1} \n" +
                                               "	AND {2} \n" ,
                                               //"ORDER BY A.Ngay \n",
                                                nhaCungCapCondition, vatTuHangHoaCondition, khoCondition);
                }

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                dsThongKeMuaHang.Detail_ThongKeMuaHang.Clear();
                da.Fill(dsThongKeMuaHang.Detail_ThongKeMuaHang);

                FormatNumberInGridView(gridView);
                FormatNumberInGridView(gridViewDsDoiTac);
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBar.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeader(true, gridControl, true, true, "Thống kê mua hàng", "");
        }
    }
}
